package com.apes.scm.masterdata.car.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;

import com.apes.scm.masterdata.car.model.MasCarBrand;
import com.apes.scm.masterdata.car.repository.MasCarBrandRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by lishikun on 2021/12/17 14:23
 */
@Service("masCarBrandService")
public class MasCarBrandService extends DomainService {

    @Autowired
    private MasCarBrandRepository masCarBrandRepository;

    public MasCarBrand carBrandSave(SimpleRequest request) {
        MasCarBrand carBrand = toCarBrandModel(request.getJO());
        return masCarBrandRepository.saveAndFlush(carBrand);
    }

    public String carBrandDelete(SimpleRequest request) {
        MasCarBrand carBrand = toCarBrandModel(request.getJO());
        try {
            masCarBrandRepository.delete(carBrand);
        } catch (Exception e) {
            throw new RuntimeException("删除失败，请检查是否已使用");
        }
        return "删除成功";
    }


    private MasCarBrand toCarBrandModel(JSONObject jsonObject) {
        MasCarBrand carBrand = SpringManager.getBean(MasCarBrandRepository.class).findOne(jsonObject.getString("QCPPID"));
        if (carBrand == null) {
            carBrand = new MasCarBrand();
            carBrand.setId(jsonObject.getString("QCPPID"));
        } else {
        }
        carBrand.setName(jsonObject.getString("QCPPMC"));
        carBrand.setValid(jsonObject.getBoolean("YXBJ"));
        return carBrand;
    }
}
